import React, { useState, useEffect } from 'react';
import {
  Form,
  SelectBox,
  TextField,
  Select,
  Tooltip,
} from 'choerodon-ui/pro';
import { observer } from 'mobx-react-lite';
import { NewTips } from '@choerodon/components';
import { get as getInject } from '@choerodon/inject';
import YamlEditor from '@/components/yamlEditor';
import OperationYaml from '@/routes/app-center-pro/components/OpenAppCreateModal/components/operation-yaml';
import Tips from '@/components/new-tips';
import StatusDot from '@/components/status-dot';
import {
  BUILD_DOCKER,
  MAVEN_BUILD,
  BUILD_MAVEN_PUBLISH,
  BUILD_UPLOADJAR,
} from '@/routes/app-pipeline/CONSTANTS';
import { deployWayData, productTypeData } from '../../stores/constants';

const { Option } = Select;

const Index = observer(({
  ds,
  hostGroupDeploy,
  deployPayloadTypeName,
  stageData,
  level,
}: any) => {
  const [relatedJobOpts, setRelatedJobOpts] = useState([]);

  useEffect(() => {
    // 应用类型是dockercompose 部署方式为禁用 更新应用
    if (ds?.current?.get('hostDeployType') === productTypeData[3].value) {
      ds?.current?.set('deployType', deployWayData[1].value);
    }
    ds?.current?.getField('deployType').set('disabled', (ds?.current?.get('hostDeployType') === productTypeData[3].value) || (level !== 'project' || window.location.href.includes('project-pipeline-template')));
  }, [ds?.current?.get('hostDeployType')]);

  useEffect(() => {
    const currentHostDeployType = ds?.current?.get('hostDeployType');
    const tempArr = stageData
    && stageData.length > 0
    && stageData.map((item: any) => item?.jobList?.slice()).filter((i: any) => i) || [];
    // @ts-ignore
    const jobArr = tempArr && tempArr.length > 0 ? [].concat.apply(...tempArr) : [];
    let filterArr;
    const alreadyPipelineTaskValue = ds?.current?.get('pipelineTask');
    if (jobArr && currentHostDeployType && currentHostDeployType === 'image') {
      filterArr = jobArr.filter(
        (x: any) => x?.devopsCiStepVOList?.some((i: any) => i?.type === BUILD_DOCKER)
        && x.type === MAVEN_BUILD,
      );
    } else if (currentHostDeployType === 'jar') {
      filterArr = jobArr.filter(
        (x: any) => (x?.devopsCiStepVOList?.some(
          (i: any) => [BUILD_MAVEN_PUBLISH, BUILD_UPLOADJAR].includes(i?.type),
        )
          && x.type === MAVEN_BUILD
        ),
      );
    } else if (['docker', 'docker_compose'].includes(currentHostDeployType)) {
      filterArr = jobArr.filter(
        (x: any) => (x?.devopsCiStepVOList?.some((i: any) => [BUILD_DOCKER].includes(i?.type))
            && x.type === MAVEN_BUILD
        ),
      );
    }
    if (filterArr && filterArr.length === 1) {
      if (typeof filterArr[0] === 'object' && !alreadyPipelineTaskValue) {
        ds.current.set('pipelineTask', filterArr[0].name);
      }
    }
    if (filterArr && filterArr.length > 0) {
      setRelatedJobOpts(filterArr);
    } else {
      setRelatedJobOpts([]);
    }
  }, [ds?.current?.get('hostDeployType')]);

  const renderEnvOption = ({ record, text }: any) => (
    <>
      <div className="option-host">
        {/* @ts-ignore */}
        <StatusDot style={{ position: 'relative', top: 1 }} size="small" synchronize connect={record?.get('connect')} />
        <span className="option-host-name">
          <Tooltip title={text}>
            {text}
          </Tooltip>
        </span>
        {
      record?.get('description') && (
      <>
        (
        <Tooltip title={record?.get('description')}>
          <span className="option-host-desc">
            {record?.get('description') }
          </span>
        </Tooltip>
        )
      </>
      )
    }
      </div>
    </>
  );

  const renderOptionProperty = ({ record }: any) => ({
    disabled: !record?.get('connect'),
  });

  const searchMatcher = ({ record, text }: any) => record?.get('pipelineTask')?.indexOf(text) !== -1;

  return (
    <>
      <Form dataSet={ds}>
        <SelectBox
          name="hostDeployType"
          onChange={(value) => {
          // 这里待修改
          // HostJarDataSet.current.set('appName', undefined);
          // HostJarDataSet.current.set('appCode', undefined);
          // HostJarDataSet.current.set('appId', undefined);
          // cdhostResetValue();
          }}
        />
        <SelectBox
          newLine
          name="deployType"
          onChange={(value) => {
          // 这里待修改
          // HostJarDataSet.current.set('appName', undefined);
          // HostJarDataSet.current.set('appCode', undefined);
          // HostJarDataSet.current.set('appId', undefined);
          // ADDCDTaskDataSet.getField(addCDTaskDataSetMap.host).set(
          //   'disabled',
          //   value === deployWayData[1].value,
          // );
          // cdhostResetValue();
          }}
        />
      </Form>
      <div className="addcdTask-divided" />
      <p
        className="addcdTask-title"
        style={{
          marginBottom: 20,
        }}
      >
        应用信息
      </p>
      <Form dataSet={ds} columns={2}>
        {
          (ds.current.get('deployType') === deployWayData[0].value
          || (hostGroupDeploy && ds.current.get(getInject('configuration.devops-routes-pipeline-manage:fieldMap').deployPayloadType.name) === 'group')// 合并分支用 1.x
          )
            ? (
              <TextField name="appName" />
            ) : (
              <Select
                name="appName"
                onChange={(value) => {
                  // handleInitDeployConfig(value);
                }}
              />
            )
        }
        <TextField
          name="appCode"
          addonAfter={hostGroupDeploy
            && ds.current.get(deployPayloadTypeName) === 'group'
            ? (
              <NewTips
                style={{
                  position: 'relative',
                  bottom: 1,
                }}
                helpText={(
                  <div>
                    <div>1. 若您在此输入已有主机应用的编码，后续流水线执行时，将会更新所选主机组中对应的主机应用。</div>
                    <div>2. 若您在此输入新主机应用的编码，后续流水线执行时，就会在所选主机组对应的主机中新建主机应用。</div>
                  </div>
                  )}
              />
            )
            : null}
        />
      </Form>
      <div className="addcdTask-divided" />
      <p className="addcdTask-title">主机部署</p>
      <Form dataSet={ds} columns={2}>
        {
          !hostGroupDeploy
          && (
          <Select
            colSpan={1}
            searchable
            searchMatcher="search_param"
            name="hostId"
            optionRenderer={renderEnvOption}
            onOption={renderOptionProperty}
          />
          )
        }
        {
          hostGroupDeploy && ds.current.get(
            deployPayloadTypeName,
          ) === 'host' && getInject('configuration.devops-routes-pipeline-manage:hostSelect')()
        }
        {
          hostGroupDeploy && ds.current.get(
            deployPayloadTypeName,
          ) === 'group' && getInject('configuration.devops-routes-pipeline-manage:hostGroupSelect')()
        }
        {
          [productTypeData[0].value, productTypeData[1].value].includes(ds.current.get('hostDeployType'))
            ? [
              <Select
                newLine
                colSpan={1}
                name="deploySource"
                clearButton={false}
                addonAfter={
                  <Tips helpText="流水线制品部署表示直接使用所选关联构建任务中生成的jar包进行部署。" />
                }
              />,
              ds.current.get('deploySource') === 'pipelineDeploy' && (
              <Select
                colSpan={3}
                name="pipelineTask"
                searchable
                addonAfter={(
                  <Tips helpText={ds?.current?.get('hostDeployType') === productTypeData[1].value
                    ? '此处的关联构建任务，仅会查询出该条流水线中存在【Docker构建】步骤的任务。'
                    : "此处的关联构建任务，仅会查询出该条流水线中存在'上传jar包至制品库'或“Maven发布”步骤的“构建类型”任务。若所选任务中存在多个满足条件的步骤，则只会部署所选任务中第一个满足条件的步骤产生的jar包；"}
                  />
                  )}
                searchMatcher={searchMatcher}
              >
                {relatedJobOpts.map((item: any) => (
                  <Option value={item.name}>{item.name}</Option>
                ))}
              </Select>
              ),
              [productTypeData[1].value].includes(ds.current.get('hostDeployType')) && (
              <TextField colSpan={1} name="containerName" />
              ),
            ] : ''
        }
        {
          [productTypeData[0].value, productTypeData[2].value].includes(ds.current.get('hostDeployType')) && (
            <OperationYaml
            // @ts-ignore
              colSpan={2}
              newLine
              hasGuide={ds.current.get('hostDeployType') === productTypeData[2].value}
              dataSet={ds}
              disabled={level !== 'project' || window.location.href.includes('project-pipeline-template')}
            // configDataSet={configDataSet}
            // optsDS={configCompareOptsDS}
              preName="preCommand"
              startName="runCommand"
              postName="postCommand"
              deleteName="killCommand"
              healthName="healthProb"
            />
          )
        }
        {
          [productTypeData[1].value].includes(ds.current.get('hostDeployType')) && (
            <YamlEditor
              colSpan={6}
                // className="addcdTask-yamleditor"
              newLine
              showError={false}
              readOnly={level !== 'project' || window.location.href.includes('project-pipeline-template')}
              value={ds.current.get('dockerCommand')}
              onValueChange={(data: any) => ds.current.set('dockerCommand', data)}
            />
          )

        }
        {
          ds.current.get('hostDeployType') === productTypeData[3].value && (
            <>
              <Select
                colSpan={3}
                name="pipelineTask"
                searchable
                addonAfter={
                  <Tips helpText="此处的关联构建任务，仅会查询出该条流水线中存在【Docker构建】步骤的任务。" />
            }
                searchMatcher={searchMatcher}
              >
                {relatedJobOpts.map((item: any) => (
                  <Option value={item.name}>{item.name}</Option>
                ))}
              </Select>
              <p
              // @ts-ignore
                colSpan={6}
                className="c7ncd-operationYaml-dockerCompose-title"
              >
                docker-compose.yml文件
                <NewTips
                  style={{
                    position: 'relative',
                    bottom: 1,
                  }}
                  helpText="此处的docker-compose.yml文件默认展示为所选应用中的yaml文件内容，且暂不支持修改。"
                />
              </p>
              <YamlEditor
                colSpan={6}
            // className="addcdTask-yamleditor"
                newLine
                modeChange={false}
                showError={false}
                readOnly
                value={ds.current.get('value')}
              />
              <p
              // @ts-ignore
                colSpan={6}
                className="c7ncd-operationYaml-dockerCompose-title"
              >
                命令
                <NewTips
                  style={{
                    position: 'relative',
                    bottom: 1,
                  }}
                  helpText="您需在此处维护操作Docker Compose的命令，此处维护的命令不会影响到主机应用中的命令；仅生效于此处的流水线主机部署任务。"
                />
              </p>
              <YamlEditor
                colSpan={6}
            // className="addcdTask-yamleditor"
                newLine
                modeChange={false}
                showError={false}
                readOnly={level !== 'project' || window.location.href.includes('project-pipeline-template')}
                value={ds.current.get('dockerComposeRunCommand')}
                onValueChange={(data: any) => ds.current.set('dockerComposeRunCommand', data)}
              />
            </>
          )
        }
      </Form>

    </>

  );
});

export default Index;
